const express = require('express')

const route = express.Router()

const adminModel = require('../db/model/adminModel')

const md5 = require('md5')

//引用jwt
const { jwtEncode
} = require('../utils/jwt')

route.post('/login', async (req, res) => {
  //后台登录逻辑
  //获取到用户名之后 去数据库查找对应的数据进行匹配
  const { adminName, password } = req.body
  //console.log(adminName);

  //console.log(findResult,'findResult');
  /*
  { adminName: 'li', password: '123', regTime: '2022/6/30 22:56:58' }
  添加信息 {
  adminName: 'li',
  password: 'd829b843a6550a947e82f2f38ed6b7a7',
  regTime: '2022/6/30 22:56:58',
  loginTime: '----',
  _id: new ObjectId("62bdb9ba730968f8f175b35d"),
  __v: 0
   */
  try {
    const findResult = await adminModel.findOne({
      adminName,
      //因为之前对密码进行了md5加密 ，所以现在需要解密
      password: md5(password + 'admin')
    })
    if (!findResult) {
      return res.send({
        code: 10002,
        mesage: '请检查:用户名密码是否正确',
        data: null
      })
    }
    //console.log(findResult, 'findResult');
    //console.log(findResult.password, 'findResult.password')
    //查询到了以后，用封装好的jwt,生成一个token进行响应
    const token = jwtEncode(findResult.adminName, 'NB!')
    // console.log(token, 'token');
    //登录成功以后 把数据库中用户的状态码改为1
    await adminModel.updateOne({
      adminName
    }, {
      $set: {
        status: 1
      }
    })
    res.send({
      code: 10000,
      mesage: '登录成功',
      data: {
        token
      }
    })

  } catch (e) {
    console.log("登录查询时发生异常", e.message);
    res.send({
      code: 10001,
      mesage: "登录查询时发生异常:" + e.message,
      data: null
    })
  }

})

module.exports = route